package deep8jvmdvm;

/*
synchronized

synchronized 可以用来修饰以下 3 个层面：

修饰实例方法；
锁对象是当前实例对象，因此只有同一个实例对象调用此方法才会产生互斥效果，不同实例对象之间不会有互斥效果

修饰静态类方法；

修饰代码块。
 */

import utils.PrintlnUtils;

public class TestSynchronized3 {

    public static void main(String[] args) {
        TestSynchronized3 testSynchronized1 = new TestSynchronized3();

        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                testSynchronized1.printLog();
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                testSynchronized1.printLog();
            }
        });
        thread1.start();
        thread2.start();

        /*
        两个线程调用同一个对象的 printLog 方法

        则执行效果如下：
        Thread-0 is printing 0

        Thread-0 is printing 1

        Thread-0 is printing 2

        Thread-0 is printing 3

        Thread-0 is printing 4

        Thread-1 is printing 0

        Thread-1 is printing 1

        Thread-1 is printing 2

        Thread-1 is printing 3

        Thread-1 is printing 4

        可以看出：只有某一个线程中的代码执行完之后，才会调用另一个线程中的代码。也就是说此时两个线程间是互斥的。

         */

    }

    public synchronized void printLog() {
        for (int i = 0; i < 5; i++) {
            PrintlnUtils.println(Thread.currentThread().getName() + " is printing " + i);
        }
    }

}
